﻿using System;
using ReAnimation.Domain;
using ReAnimation.Domain.Policies.Interfaces;
using ReAnimation.Domain.Policies.Interfaces.ErrorEnums;
using ReAnimation.Helpers.Common;
using ReAnimation.Helpers.IoC;
using ReAnimation.Helpers.WinForms;
using ReAnimation.MVP.Models.Interfaces;
using ReAnimation.MVP.ViewInterfaces;
using ReAnimation.Infrastructure.Services.DomainFactories.Interfaces;


namespace ReAnimation.MVP.Presenters
{
    public class NewMoleculeDialogPresenter: BasePresenter<INewMoleculeDialogView>
    {
        private IMainModel _mainModel;
        private IMainPresentationModel _mainPresentationModel;
        private IMoleculePolicy _moleculePolicy;
        private ILazyInject<INotifier> _notifier;
        private IMoleculeFactory _moleculeFactory;

        public NewMoleculeDialogPresenter(IMainModel mainModel, 
                                          IMainPresentationModel mainPresentationModel,
                                          IMoleculePolicy moleculePolicy,
                                          ILazyInject<INotifier> notifier,
                                          IMoleculeFactory moleculeFactory)
        {
            _mainModel = mainModel;
            _mainPresentationModel = mainPresentationModel;
            _moleculePolicy = moleculePolicy;
            _notifier = notifier;
            _moleculeFactory = moleculeFactory;
        }

        protected override void InitView()
        {
            _view.Create += ViewOnCreate;
            _view.ViewClosed += ViewOnViewClosed;
        }

        private void ViewOnViewClosed(object sender, EventArgs eventArgs)
        {
            _view.Create -= ViewOnCreate;
            _view.ViewClosed -= ViewOnViewClosed;
        }

        private void ViewOnCreate(object sender, EventArg<string> eventArg)
        {
            ValidationResult<IncorrectMoleculeNameErrors> validationResult = _moleculePolicy.CheckName(eventArg.Data);
            if (!validationResult.IsError)
            {
                var molecule = _moleculeFactory.CreateMolecule();
                molecule.Name = eventArg.Data;
                _mainModel.CurrentAnimationStep.AddMolecule(molecule);
                _mainModel.CurrentMolecule = molecule;
                _view.Close();
            }
            else
            {
                //TODO: need an resource with the all strings for errors
                _notifier.Get().ShowMessage("Error",validationResult.Error.ToString());
            }
        }
    }
}
